package flink;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.AssignerWithPeriodicWatermarks;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.util.Collector;
import org.apache.flink.util.StringUtils;


/**
 * Created by liujian on 2021/3/3.
 */
public class KeyedProcess {

    public static void main(String[] args) throws Exception{
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime);

        // 监听
        DataStream<String> socketDataStream = env.socketTextStream("192.168.62.34", 9999);
        DataStream<Tuple2<String, Long>> timeOutWord = socketDataStream.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                if(StringUtils.isNullOrWhitespaceOnly(s)) {
                    System.out.println("invalid line");
                    return;
                }

                for(String word : s.split(" ")) {
                    collector.collect(new Tuple2<String, Integer>(word, 1));
                }
            }
        }).assignTimestampsAndWatermarks(new AssignerWithPeriodicWatermarks<Tuple2<String, Integer>>() {
            @Override
            public Watermark getCurrentWatermark() {
                return null;
            }

            @Override
            public long extractTimestamp(Tuple2<String, Integer> element, long recordTimestamp) {
                return System.currentTimeMillis();
            }
        }).keyBy(0)
        .process(new CountWithTimeoutFunction());

        timeOutWord.print();
        env.execute("App");

    }

}



